package com.example.musicplayer.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.musicplayer.R;

public class StrokeTextView extends androidx.appcompat.widget.AppCompatTextView {
    private TextView mTextView = null;
    private int mStrokeColor;
    private float mStrokeWidth;

    public StrokeTextView(Context context) {
        this(context, null);
    }

    public StrokeTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public StrokeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mTextView = new TextView(context, attrs, defStyleAttr);
        mStrokeColor = Color.BLACK;
        mStrokeWidth = 1.0f;
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.StrokeTextView);
        mStrokeColor = typedArray.getColor(R.styleable.StrokeTextView_strokeTextColor, mStrokeColor);
        mStrokeWidth = typedArray.getFloat(R.styleable.StrokeTextView_strokeTextWidth, mStrokeWidth);
        typedArray.recycle();
        init();
    }

    private void init() {
        TextPaint paint = mTextView.getPaint();
        paint.setStrokeWidth(mStrokeWidth);
        paint.setStyle(Paint.Style.STROKE);
        mTextView.setTextColor(mStrokeColor);
        mTextView.setGravity(getGravity());
    }

    @Override
    public void setLayoutParams(ViewGroup.LayoutParams params) {
        super.setLayoutParams(params);
        mTextView.setLayoutParams(params);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mTextView.measure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        mTextView.layout(left, top, right, bottom);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        mTextView.draw(canvas);
        super.onDraw(canvas);
        //set text for stroke text view
        String strokeText = (String) mTextView.getText();
        if (strokeText == null || !strokeText.equals((String) getText())) {
            mTextView.setText(getText());
            postInvalidate();
        }
    }
}